#include "widget.h"
#include "ui_widget.h"

#include "application.h"
#include <QtWebKit>

#include "t_youtube_dump_lib.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject()));
#if 0x1
    QNetworkDiskCache *v_disk_cache = new QNetworkDiskCache(this);
    QString v_cache_location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
    qDebug() << "[v_cache_location]" << v_cache_location;
    v_disk_cache->setCacheDirectory(v_cache_location);
    ui->webView->page()->networkAccessManager()->setCache(v_disk_cache);
#endif
    this->resize(800, 600);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::populateJavaScriptWindowObject()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("web1", this);
    //ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("list1", &this->m_video_list);
    //ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("page1", g_Env->page1);

}

void Widget::dbgmsg(QString v_msg)
{
    qDebug(v_msg.toLocal8Bit().constBegin());
}

void Widget::submitIdToPlay(QString a_id)
{
#if 0x0
    QFile v_program;
    v_program.setFileName(QString("C:\\Program Files\\SMPlayer\\smplayer.exe"));
    QString v_url = QString("http://www.youtube.com/watch?v=%1").arg(a_id);
    QStringList v_arguments;
    v_arguments << v_url;
    QProcess::startDetached(v_program.fileName(), v_arguments);
#else
    qDebug() << "[a_id]" << a_id;
    QMap<int, QUrl> v_fmt_map;
    QStringList v_error_list;

    QString v_token = T_Youtube_Dump_Lib::getVideoStreamMap(
                ui->webView->page()->networkAccessManager(), a_id, v_fmt_map, v_error_list);
    if(v_token.isEmpty())
    {
        return;
    }
    if(v_fmt_map.contains(18))
    {
        qDebug() << "[v_fmt_map.value(18)]" << v_fmt_map.value(18);
        QString v_url_str = v_fmt_map.value(18).toString();
        QFile v_program;
        v_program.setFileName(QString("C:\\Program Files\\SMPlayer\\smplayer.exe"));
        //QString v_url = QString("http://www.youtube.com/watch?v=%1").arg(a_id);
        QStringList v_arguments;
        v_arguments << v_url_str;
        QProcess::startDetached(v_program.fileName(), v_arguments);
    }
    else
    {
        return;
    }
#endif
}

void Widget::submitIdToDownload(QString a_id)
{
    QFile v_program;
    T_Youtube_Dump_Lib::getDownloadExe(v_program);
    v_program.fileName();
    QStringList v_arguments;
    v_arguments << a_id;
    QProcess::startDetached(v_program.fileName(), v_arguments);
}

void Widget::on_pushButton_clicked()
{
    Application *v_app = (Application *)qApp;
    QString v_htmlText2 = v_app->generateTestHtml();
    ui->webView->setHtml(v_htmlText2);
}
